import {listFeatureServices} from '@/api/sjwh'
import SmQuery from '@/assets/js/utils/SmQuery'
import axios from 'axios';

const sjwh = {
  namespaced:true,
  state: {
    map: undefined,                             //数据维护Map
    mapService: undefined,                      //Map操作了类
    featureCollection: [],                      //当前显示服务要素
    featureService: [],                         //要素服务集合
    featuresCache: {},                          //要素服务缓存
    selectFeature: undefined,                   //当前选中的服务
    drawControl: undefined,                     //drawControl组件
    editTableVisible: undefined,                //编辑属性表的显隐
    featureFieldsCache: {},                      //服务字段属性缓存
    featureFields: undefined,                     //要素服务的属性集合

  },

  mutations: {
    setMap: (state, map) => {
      state.map = map
    },
    setSjwhMapService: (state, mapservice) => {
      state.mapService = mapservice;
    },
    setFeatureCollection: (state, features) => {
      state.featureCollection = features;
    },
    setFeatureService: (state, featureservice) => {
      state.featureService = featureservice;
    },
    setSelectFeature: (state, feature) => {
      state.selectFeature = feature;
    },
    setDrawControl: (state, drawControl) => {
      state.drawControl = drawControl;
    },
    setEditTableVisible: (state, isVisible) => {
      state.editTableVisible = isVisible;
    },
    setFeaturesCache: (state, cache) => {
      state.featuresCache = cache;
    },
    setFeatureFields: (state, cache) => {
      state.featureFields = cache;
    }
  },

  actions: {
    /**
     * 获取编辑要素服务
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     * @constructor
     */
    ListFSs({commit, state}) {
      return new Promise((resolve, reject) => {
        listFeatureServices({dept: this.getters.dept}).then(res => {
          commit('setFeatureService', res.data);
          resolve(res.data)
        }).catch(e => {
          reject(e);
        })
      })

    },
    /**
     * 切换服务 并请求数据
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     */
    requestSmServerRestData({commit, state}, param) {
      return new Promise((resolve, reject) => {
        commit('setSelectFeature', param);      //设置选中当前图层
        commit('setEditTableVisible', true);    //显示数据
        commit('setFeatureCollection', []);
        try {
          if (param.url) {
            const urlArray = param.url.split('?');
            const temp = param.url.replace(urlArray[urlArray.length - 1], '');
            const realUrl = param.url.replace(urlArray[urlArray.length - 1], '').substring(0, temp.length - 1);
            const obj = JSON.parse('{"' +
              decodeURIComponent(urlArray[urlArray.length - 1])
                .replace(/"/g, '\\"')
                .replace(/&/g, '","')
                .replace(/=/g, '":"') +
              '"}'
            )
            //判断是否缓存了数据，没有数据请求数据，存在数据
            if (state.featuresCache[param._id]) {
              state.drawControl.set(state.featuresCache[param._id]);
              commit('setFeatureCollection', state.featuresCache[param._id].features);
              resolve();
            } else {
              if (obj.dataSourceName && obj.dataSetName) {
                SmQuery.getFeaturesBySQL(realUrl, obj.dataSourceName, obj.dataSetName).then(res => {
                  state.drawControl.set(res.result ? res.result.features : []);
                  commit('setFeatureCollection', state.drawControl.getAll().features);
                  state.featuresCache[param._id] = res.result ? res.result.features : [];   //FeatureCollection

                  resolve();
                }).catch(e => {
                  reject(e);
                })
              } else {
                state.drawControl.deleteAll();
                commit('setFeatureCollection', []);
                reject('接入超图要素服务URL解析,没有发现dataSourceName或者dataSetName的值!');
              }

            }
            //请求要素字段
            if (state.featureFieldsCache[param._id]) {
              commit('setFeatureFields', state.featureFieldsCache[param._id]);
            } else {
              axios.get(realUrl + '/datasources/name/' + obj.dataSourceName + '/datasets/name/' + obj.dataSetName + '/fields.rjson?returnAll=true').then(res => {
                state.featureFieldsCache[param._id] = res.data;
                commit('setFeatureFields', res.data);
              }).catch(e => {
                reject(e);
              })
            }

          }
        } catch (e) {
          state.drawControl.deleteAll();
          commit('setFeatureCollection', []);
          reject("要素服务URL参数配置不正确，不能正常解析的JSON")
          // console.log("要素服务URL参数配置不正确，不能正常解析的JSON");
        }

      })
    },

    /**
     * 添加要素
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     * @constructor
     */
    AddFeature({commit, state}, param) {
      return new Promise((resolve, reject) => {
        const urlArray = state.selectFeature.url.split('?');
        const temp = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '');
        const realUrl = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '').substring(0, temp.length - 1);
        try {
          var obj = JSON.parse('{"' +
            decodeURIComponent(urlArray[urlArray.length - 1])
              .replace(/"/g, '\\"')
              .replace(/&/g, '","')
              .replace(/=/g, '":"') +
            '"}'
          )
          if (obj.dataSourceName && obj.dataSetName) {
            SmQuery.addFeatures(realUrl, param, obj.dataSourceName, obj.dataSetName, false, true).then(res => {
              //两种方案
              //1、
              if (res.result) {
                const tempIds = param.map(o => o.id);
                const newFeatures = tempIds.map((o, i) => {
                  const newFeature = state.drawControl.get(o);
                  newFeature.id = res.result[i];
                  return newFeature;
                });
                state.drawControl.delete(tempIds);
                state.drawControl.add({type: 'FeatureCollection', features: newFeatures});
                state.drawControl.changeMode('simple_select', {featureIds: res.result});//高亮
                commit('setFeatureCollection', state.drawControl.getAll().features);
                //更新缓存
                state.featuresCache[state.selectFeature._id] = state.drawControl.getAll();   //FeatureCollection
                resolve(res.result);
              }

            }).catch(e => {
              reject(e);
            })
          } else {
            reject('接入超图要素服务URL解析,没有发现dataSourceName或者dataSetName的值!');
          }
        } catch (e) {
          console.warn("要素服务URL参数配置不正确，不能正常解析的JSON");
        }
      });
    },

    /**
     * 删除要素
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     * @constructor
     */
    RemoveFeatures({commit, state}, param) {
      return new Promise((resolve, reject) => {
        const urlArray = state.selectFeature.url.split('?');
        const temp = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '');
        const realUrl = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '').substring(0, temp.length - 1);
        try {
          var obj = JSON.parse('{"' +
            decodeURIComponent(urlArray[urlArray.length - 1])
              .replace(/"/g, '\\"')
              .replace(/&/g, '","')
              .replace(/=/g, '":"') +
            '"}'
          )
          if (obj.dataSourceName && obj.dataSetName) {
            const ids = param.map(o => o.id);
            SmQuery.removeFeatures(realUrl, param, obj.dataSourceName, obj.dataSetName, true, ids, true).then(res => {
              if (res.result.succeed) {
                state.drawControl.delete(ids);
                commit('setFeatureCollection', state.drawControl.getAll().features);
                //更新缓存
                state.featuresCache[state.selectFeature._id] = state.drawControl.getAll();   //FeatureCollection
                resolve(res);
              } else {
                reject('服务删除失败!');
              }
            }).catch(e => {
              reject(e);
            })
          } else {
            reject('接入超图要素服务URL解析,没有发现dataSourceName或者dataSetName的值!');
          }
        } catch (e) {
          console.log(e);
          reject(e);
        }
      })
    },

    /**
     * 更新要素
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     * @constructor
     */
    UpdateFeature({commit, state}, param) {
      return new Promise((resolve, reject) => {
        const urlArray = state.selectFeature.url.split('?');
        const temp = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '');
        const realUrl = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '').substring(0, temp.length - 1);
        try {
          var obj = JSON.parse('{"' +
            decodeURIComponent(urlArray[urlArray.length - 1])
              .replace(/"/g, '\\"')
              .replace(/&/g, '","')
              .replace(/=/g, '":"') +
            '"}'
          )
          if (obj.dataSourceName && obj.dataSetName) {
            SmQuery.updateFeatures(realUrl, param, obj.dataSourceName, obj.dataSetName, false, false).then(res => {
              if (res.result.succeed) {    //成功
                for (let k in param[0].properties) {    //设置属性
                  state.drawControl.setFeatureProperty(param[0].id, k, param[0].properties[k]);
                }
                commit('setFeatureCollection', state.drawControl.getAll().features);
                //更新缓存
                state.featuresCache[state.selectFeature._id] = state.drawControl.getAll();   //FeatureCollection
                resolve(res);
              } else {
                reject('服务更新失败!');
              }
            }).catch(e => {
              reject('SmQuery.updateFeatures出错', e);
            })
          } else {
            reject('接入超图要素服务URL解析,没有发现dataSourceName或者dataSetName的值!');
          }
        } catch (e) {
          console.warn("要素服务URL参数配置不正确，不能正常解析的JSON", e);
          reject(e);
        }
      });
    },
    /**
     * excel批量添加
     * @param commit
     * @param state
     * @param param
     * @returns {Promise<any>}
     * @constructor
     */
    BatchAddFeature({commit, state}, param) {
      return new Promise((resolve, reject) => {
        const urlArray = state.selectFeature.url.split('?');
        const temp = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '');
        const realUrl = state.selectFeature.url.replace(urlArray[urlArray.length - 1], '').substring(0, temp.length - 1);
        try {
          var obj = JSON.parse('{"' +
            decodeURIComponent(urlArray[urlArray.length - 1])
              .replace(/"/g, '\\"')
              .replace(/&/g, '","')
              .replace(/=/g, '":"') +
            '"}'
          )
          if (obj.dataSourceName && obj.dataSetName) {
            SmQuery.addFeatures(realUrl, param, obj.dataSourceName, obj.dataSetName, false, true).then(res => {
              //两种方案
              //1、
              if (res.result) {
                const newFeatures = param.map((o, i) => {
                  o.id = res.result[i];
                  return o;
                });
                state.drawControl.add({type: 'FeatureCollection', features: newFeatures});
                state.drawControl.changeMode('simple_select', {featureIds: res.result});//高亮
                commit('setFeatureCollection', state.drawControl.getAll().features);
                //更新缓存
                state.featuresCache[state.selectFeature._id] = state.drawControl.getAll();   //FeatureCollection
                resolve(res.result);
              }

            }).catch(e => {
              reject(e);
            })
          } else {
            reject('接入超图要素服务URL解析,没有发现dataSourceName或者dataSetName的值!');
          }
        } catch (e) {
          console.warn("要素服务URL参数配置不正确，不能正常解析的JSON", e);
        }
      });
    },


  }


}
export default sjwh
